/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.davidhodin.easymoney.ihm;

import com.davidhodin.easymoney.data.Categorie;
import com.davidhodin.easymoney.data.Compte;
import com.davidhodin.easymoney.data.CompteJpaController;
import com.davidhodin.easymoney.data.Mouvement;
import com.davidhodin.easymoney.data.MouvementJpaController;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.swing.JOptionPane;

/**
 *
 * @author David
 */
public class IhmMouvement extends javax.swing.JDialog {
    // Données

    private String nomCompte;
    private String nomCategorie;
    private Mouvement mvt;
    private MouvementJpaController controleurMvt;
    private CompteJpaController controleurCpt;
    private JOptionPane opp = new JOptionPane();
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");

    /**
     * Creates new form IhmMouvement
     *
     * @param parent
     * @param modal
     */
    public IhmMouvement(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    /**
     *
     * @param mvt
     */
    public void setMvt(Mouvement mvt) {
        // Récupère le mouvement et actualise les données d'affichage
        this.mvt = mvt;
        jTextFieldMontantMvt.setText(mvt.getMontantOp().toString());
        jTextFieldDateMvt.setText(simpleDateFormat.format(mvt.getDateOperation()));
        jTextAreaOperation.setText(mvt.getDetailOperation());
        if (mvt.getCredit() == 1) {
            jRadioButtonCredit.setSelected(true);
        }
    }

    /**
     *
     * @param nomCategorie
     * @param listCat
     */
    public void setNomCategorie(String nomCategorie, List<Categorie> listCat) {
        this.nomCategorie = nomCategorie;
        for (Categorie cat : listCat) {
            jComboBoxCat.addItem(cat.getNomCategorie());
        }
        if (!nomCategorie.isEmpty()) {
            jComboBoxCat.setSelectedItem(nomCategorie);
        } else {
            this.nomCategorie = (String) jComboBoxCat.getItemAt(0);
        }
    }

    /**
     *
     * @param nomCompte
     * @param lisCpt
     */
    public void setNomCompte(String nomCompte, List<Compte> lisCpt) {
        this.nomCompte = nomCompte;
        for (Compte cpt : lisCpt) {
            jComboBoxCpte.addItem(cpt.getNomCompte());
        }
        jComboBoxCpte.setSelectedItem(nomCompte);

    }

    /**
     *
     * @param controleurMvt
     */
    public void setControleurMvt(MouvementJpaController controleurMvt) {
        this.controleurMvt = controleurMvt;
    }

    /**
     *
     * @param controleurCpt
     */
    public void setControleurCpt(CompteJpaController controleurCpt) {
        this.controleurCpt = controleurCpt;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        buttonGroupDebitCredit = new javax.swing.ButtonGroup();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jTextFieldMontantMvt = new javax.swing.JTextField();
        jTextFieldDateMvt = new javax.swing.JFormattedTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextAreaOperation = new javax.swing.JTextArea();
        jPanel3 = new javax.swing.JPanel();
        jRadioButtonDebit = new javax.swing.JRadioButton();
        jRadioButtonCredit = new javax.swing.JRadioButton();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jComboBoxCat = new javax.swing.JComboBox();
        jComboBoxCpte = new javax.swing.JComboBox();
        jPanel2 = new javax.swing.JPanel();
        jButtonValider = new javax.swing.JButton();
        jButtonAnnuler = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Mouvement");
        setLocationByPlatform(true);
        setResizable(false);
        getContentPane().setLayout(new java.awt.BorderLayout(10, 10));

        jPanel1.setBorder(javax.swing.BorderFactory.createEmptyBorder(10, 10, 10, 10));
        java.awt.GridBagLayout jPanel1Layout = new java.awt.GridBagLayout();
        jPanel1Layout.columnWidths = new int[] {0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0};
        jPanel1Layout.rowHeights = new int[] {0, 5, 0, 5, 0, 5, 0, 5, 0, 5, 0};
        jPanel1.setLayout(jPanel1Layout);

        jLabel1.setText("Montant du mouvement :");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
        jPanel1.add(jLabel1, gridBagConstraints);

        jLabel2.setText("Date du mouvement :");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
        jPanel1.add(jLabel2, gridBagConstraints);

        jLabel3.setText("Détail de l'opération :");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 4;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
        jPanel1.add(jLabel3, gridBagConstraints);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        jPanel1.add(jTextFieldMontantMvt, gridBagConstraints);

        jTextFieldDateMvt.setToolTipText("");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        jPanel1.add(jTextFieldDateMvt, gridBagConstraints);

        jTextAreaOperation.setColumns(20);
        jTextAreaOperation.setRows(5);
        jScrollPane1.setViewportView(jTextAreaOperation);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 4;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        jPanel1.add(jScrollPane1, gridBagConstraints);

        jPanel3.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));

        buttonGroupDebitCredit.add(jRadioButtonDebit);
        jRadioButtonDebit.setSelected(true);
        jRadioButtonDebit.setText("Débit");
        jRadioButtonDebit.setActionCommand("débit");
        jPanel3.add(jRadioButtonDebit);

        buttonGroupDebitCredit.add(jRadioButtonCredit);
        jRadioButtonCredit.setText("Crédit");
        jRadioButtonCredit.setActionCommand("crédit");
        jPanel3.add(jRadioButtonCredit);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 6;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        jPanel1.add(jPanel3, gridBagConstraints);

        jLabel4.setText("Catégorie du mouvement :");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 8;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
        jPanel1.add(jLabel4, gridBagConstraints);

        jLabel5.setText("Compte du mouvement :");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 10;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
        jPanel1.add(jLabel5, gridBagConstraints);

        jComboBoxCat.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBoxCatActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 8;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        jPanel1.add(jComboBoxCat, gridBagConstraints);

        jComboBoxCpte.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBoxCpteActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 10;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        jPanel1.add(jComboBoxCpte, gridBagConstraints);

        getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);

        jButtonValider.setText("Valider");
        jButtonValider.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonValiderActionPerformed(evt);
            }
        });
        jPanel2.add(jButtonValider);

        jButtonAnnuler.setText("Annuler");
        jButtonAnnuler.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAnnulerActionPerformed(evt);
            }
        });
        jPanel2.add(jButtonAnnuler);

        getContentPane().add(jPanel2, java.awt.BorderLayout.SOUTH);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonValiderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonValiderActionPerformed
        // tests puis ajout ou modification du mouvement
        Float montant;
        Date date = null;

        try {
            montant = Float.valueOf(jTextFieldMontantMvt.getText());
        } catch (Exception e) {
            opp.showMessageDialog(this, "La valeur du montant doit être un nombre (le \".\" est utilisé pour la virgule", "Erreur", JOptionPane.ERROR_MESSAGE);
            return;
        }
        // teste le signe du montant
        if (montant < 0) {
            opp.showMessageDialog(this, "Le montant ne peut pas être négatif", "Erreur", JOptionPane.ERROR_MESSAGE);
            return;
        }
        if (!jTextFieldDateMvt.getText().equals("")) {
            try {
                date = simpleDateFormat.parse(jTextFieldDateMvt.getText());
            } catch (Exception e) {
                opp.showMessageDialog(this, "La date doit être correctement formatée (ex : 31/12/2012)", "Erreur", JOptionPane.ERROR_MESSAGE);
                return;
            }
        }

        // crée ou met à jour le mouvement
        if (mvt == null) {
            // création
            try {
                // met à jour le solde du compte
                Compte aMettreAjour = controleurCpt.findCompte(nomCompte);
                try {
                    if (jRadioButtonCredit.isSelected()) {
                        // c'est un crédit
                        aMettreAjour.setMontantCompte(aMettreAjour.getMontantCompte() + montant);
                        controleurCpt.edit(aMettreAjour);
                    } else {
                        // c'est un débit
                        aMettreAjour.setMontantCompte(aMettreAjour.getMontantCompte() - montant);
                        controleurCpt.edit(aMettreAjour);
                    }
                } catch (Exception e) {
                    opp.showMessageDialog(this, "Erreur de mise à jour du montant de compte : " + e.toString(), "Erreur", JOptionPane.ERROR_MESSAGE);
                    return;
                }
                // Ajout du mouvement
                mvt = new Mouvement();
                mvt.setCategorie(nomCategorie);
                mvt.setCompte(nomCompte);
                mvt.setMontantOp(montant);
                if (date == null) {
                    mvt.setDateOperation(new Date());
                } else {
                    mvt.setDateOperation(date);
                }
                mvt.setDetailOperation(jTextAreaOperation.getText());
                if (jRadioButtonCredit.isSelected()) {
                    mvt.setCredit((short) 1);
                } else {
                    mvt.setCredit((short) 0);
                }
                // Création du mouvement
                controleurMvt.create(mvt);
                // Mise à jour du solde du compte

                // sortie
                this.dispose();

            } catch (Exception e) {
                opp.showMessageDialog(this, "Erreur d'enregistrement du mouvement : " + e.toString(), "Erreur", JOptionPane.ERROR_MESSAGE);
                return;
            }


        } else {
            // met à jour le solde du compte          
            Compte aMettreAjour = controleurCpt.findCompte(nomCompte);
            try {
                // Supprime les anciennes données
                if (mvt.getCredit() == 1) {
                    aMettreAjour.setMontantCompte(aMettreAjour.getMontantCompte() - mvt.getMontantOp());
                } else {
                    aMettreAjour.setMontantCompte(aMettreAjour.getMontantCompte() + mvt.getMontantOp());
                }
                // Ajoute les nouvelles données
                if (jRadioButtonCredit.isSelected()) {
                    // c'est un crédit
                    aMettreAjour.setMontantCompte(aMettreAjour.getMontantCompte() + montant);
                    controleurCpt.edit(aMettreAjour);
                } else {
                    // c'est un débit
                    aMettreAjour.setMontantCompte(aMettreAjour.getMontantCompte() - montant);
                    controleurCpt.edit(aMettreAjour);
                }
            } catch (Exception e) {
                opp.showMessageDialog(this, "Erreur de mise à jour du montant de compte : " + e.toString(), "Erreur", JOptionPane.ERROR_MESSAGE);
                return;
            }

            // modification du mouvement
            try {
                mvt.setCategorie(nomCategorie);
                mvt.setCompte(nomCompte);
                mvt.setMontantOp(montant);
                mvt.setDetailOperation(jTextAreaOperation.getText());
                if (date == null) {
                    mvt.setDateOperation(new Date());
                } else {
                    mvt.setDateOperation(date);
                }
                if (jRadioButtonCredit.isSelected()) {
                    mvt.setCredit((short) 1);
                } else {
                    mvt.setCredit((short) 0);
                }
                // Création du mouvement
                controleurMvt.edit(mvt);
                // Mise à jour du solde du compte

                // sortie
                this.dispose();

            } catch (Exception e) {
                opp.showMessageDialog(this, "Erreur d'enregistrement du mouvement : " + e.toString(), "Erreur", JOptionPane.ERROR_MESSAGE);
                return;
            }
        }


    }//GEN-LAST:event_jButtonValiderActionPerformed

    private void jButtonAnnulerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAnnulerActionPerformed
        // Quitte
        this.dispose();
    }//GEN-LAST:event_jButtonAnnulerActionPerformed

    private void jComboBoxCatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxCatActionPerformed
        // prend la valeur en cours
        this.nomCategorie = jComboBoxCat.getSelectedItem().toString();
    }//GEN-LAST:event_jComboBoxCatActionPerformed

    private void jComboBoxCpteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxCpteActionPerformed
        // prend la valeur en cours
        this.nomCompte = jComboBoxCpte.getSelectedItem().toString();
    }//GEN-LAST:event_jComboBoxCpteActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(IhmMouvement.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(IhmMouvement.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(IhmMouvement.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(IhmMouvement.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the dialog
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                throw new UnsupportedOperationException("Not supported yet.");
            }
//            public void run() {
//                IhmMouvement dialog = new IhmMouvement(new javax.swing.JFrame(), true);
//                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
//
//                    @Override
//                    public void windowClosing(java.awt.event.WindowEvent e) {
//                        System.exit(0);
//                    }
//                });
//                dialog.setVisible(true);
//            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroupDebitCredit;
    private javax.swing.JButton jButtonAnnuler;
    private javax.swing.JButton jButtonValider;
    private javax.swing.JComboBox jComboBoxCat;
    private javax.swing.JComboBox jComboBoxCpte;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JRadioButton jRadioButtonCredit;
    private javax.swing.JRadioButton jRadioButtonDebit;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextAreaOperation;
    private javax.swing.JFormattedTextField jTextFieldDateMvt;
    private javax.swing.JTextField jTextFieldMontantMvt;
    // End of variables declaration//GEN-END:variables
}
